#include "ActionTopic.h"
#include "json.h"
#include "util.h"
#include "streamdata.h"
#include "ActionAgencyEventListen.h"


std::map<std::int32_t, std::function<void(const topic_proto::Topic&)>> ActionTopic::m_topic_listen;

bool ActionTopic::Init()
{
    log_info("enter");
    Ctx.msg_router.BindMsg(topic_proto::TOPIC_CMD_DISPATCH_PUSH, ActionTopic::HandleTopicDispatch);

    ListenTopicUpdate(topic_proto::TopicEvent::TOPIC_EVENT_AGENCY_EVENT_UPDATE, ActionAgencyEventListen::OnAgencyEventUpdate);
    return true;
}

void ActionTopic::HandleTopicDispatch(MsgData&& msg_data)
{
    topic_proto::Topic topic;
    do {
        if (!topic.ParseFromArray(msg_data.data.data(), msg_data.data.size()))
        {
            log_error("parser topic_proto::Topic failed");
            break;
        }

        log_debug("topic:%s", topic.ShortDebugString().c_str());
        OnTopicUpdate(topic);
        return;
    } while(false);
}

void ActionTopic::OnTopicUpdate(const topic_proto::Topic& topic)
{
    try
    {
        auto it = m_topic_listen.find(topic.topic_event());
        if(it != m_topic_listen.end())
        {
            it->second(topic);
        }
    }
    catch(const std::exception& e)
    {
        log_warning("catch exception,%s,%s", e.what(), topic.ShortDebugString().c_str());
    }
    catch(...)
    {
        log_warning("catch unknown exception,%s", topic.ShortDebugString().c_str());
    }
}

void ActionTopic::ListenTopicUpdate(std::int32_t topic_event, std::function<void(const topic_proto::Topic&)> listen)
{
    log_info("listen event:%d", topic_event);
    m_topic_listen.emplace(topic_event, listen);
}






